package crawler.client.core.handle;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import crawler.client.core.Execute;
import crawler.client.core.configure.ClientCoreConfigure;

@Service
public class PathHandle {

	private static Logger log = LoggerFactory.getLogger(PathHandle.class);

	private String javaPath;

	private ClientCoreConfigure clientCoreConfigure;

	@Autowired
	public PathHandle(ClientCoreConfigure clientCoreConfigure) {
		this.clientCoreConfigure = clientCoreConfigure;

		this.javaPath = clientCoreConfigure.getScriptPath() + "/java/";
	}

	public String getBasePath() throws UnsupportedEncodingException {
		URL base = Execute.class.getProtectionDomain().getCodeSource().getLocation();

		String basePath = URLDecoder.decode(base.getPath(), "utf-8");
		log.info("getBasePath : Base Path : " + basePath);

		if (basePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
			// 截取路径中的jar包名
			basePath = basePath.substring(0, basePath.lastIndexOf("/") + 1);
		}

		log.info("getBasePath : Path : " + basePath);
		return basePath;
	}

	public String getScriptPath(Integer scriptType) throws UnsupportedEncodingException {
		String scriptPath = getBasePath();

		if (scriptType == 1) {
			scriptPath = scriptPath + javaPath;
		}

		log.info("Script Path : " + scriptPath);
		return scriptPath;
	}
}
